<?php

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Events\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Register\Form\RegisterForm;
use Events\model\Register;
use Register\model\Participant;
use Register\model\ParticipantPhone;
use Register\model\ParticipantEmail;

class EventParticipantController extends AbstractActionController
{
    protected $form;
    protected $authservice;    
    protected $userinfo;    
    protected $eventTable;    
    protected $registerTable;    
    protected $participantTable;
    protected $dbConnection;
	protected $participantPhoneTable;
	protected $participantEmailTable;

    private function processRegistrationData($data) {
        $data['FK_PARTICIPANT_ID']=$data['ID'];
        $data['FK_EVENT_ID']=$data['PENDINGEVENT'];
        return $data;
    }
    
    private function processData($data) {
        $data['ID']=$this->generateID();
        return $data;
    }
    
    private function generateID(){
        $table_key = '1002';
        $key = $table_key.time();
        return $key;
    }
    
    public function getAuthService()
    {
        if (! $this->authservice) {
            $this->authservice = $this->getServiceLocator()->get('AuthService');
        }
        return $this->authservice;
    }
    
    public function getDbConnection(){
        if (! $this->dbConnection) {
            $this->dbConnection = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter')->getDriver()->getConnection();
        }
        return $this->dbConnection;
    }
    
    public function getUserInfo()
    {
        if ($this->getAuthService()->getIdentity()) {
            $this->userinfo = $this->getAuthService()->getStorage()->read();
        }
        return $this->userinfo;
    }
    
    public function getEventTable()
    {
        if(! $this->eventTable) {
            $this->eventTable = $this->getServiceLocator()->get('Event\Model\EventTable');
        }
        return $this->eventTable;
    }

    public function getRegisterTable()
    {
        if(! $this->registerTable) {
            $this->registerTable = $this->getServiceLocator()->get('Event\Model\RegisterTable');
        }
        return $this->registerTable;
    }
    
    public function getParticipantTable()
    {        
        if(! $this->participantTable) {
            $this->participantTable = $this->getServiceLocator()->get('Register\Model\ParticipantTable');
        }
        return $this->participantTable;
    }
    public function getParticipantPhoneTable()
    {
        if(! $this->participantPhoneTable) {
            $this->participantPhoneTable = $this->getServiceLocator()->get('Register\Model\ParticipantPhoneTable');
        }
        return $this->participantPhoneTable;
    }
    
    public function getParticipantEmailTable()
    {
        if(! $this->participantEmailTable) {
            $this->participantEmailTable = $this->getServiceLocator()->get('Register\Model\ParticipantEmailTable');
        }
        return $this->participantEmailTable;
    }
    protected function createParticipant(array $data,$type)
    {
        $participant=new Participant();
	    $participant->exchangeArray($data);
	    $participant_phone=new ParticipantPhone();
	    $participant_phone->exchangeArray($data);
	    $participant_email=new ParticipantEmail();
	    $participant_email->exchangeArray($data);
	    
	    $this->getParticipantTable()->saveParticipant($participant,$type);
	    $this->getParticipantPhoneTable()->saveParticipantPhone($participant_phone, $type);
	    $this->getParticipantEmailTable()->saveParticipantEmail($participant_email, $type);
	    return true;
    }    
    protected function createRegister(array $data)
    {
        $register=new Register();
        $register->exchangeArray($data);
        $this->getRegisterTable()->saveRegister($register);
        return true;
    }
    
/*Actions*/
    public function indexAction()
    {
        $this->layout()->setTemplate('layout/eventparticipantlayout');
        $event_id = $this->params()->fromRoute('id');
        $this->layout()->id=$event_id;        
        
        if ($this->getAuthService()->getIdentity()) {
            
                $userinfo = $this->getUserInfo();
                $this->layout()->role= $userinfo->ROLE;
                $this->layout()->user=$userinfo->USERNAME;
                
                if (! $userinfo->ROLE == 'admin') {
                    return $this->redirect()->toRoute('Login');
                }
                
          if($this->params()->fromRoute('id')!== null)
          {     
                 $pendingEvent = $this->getEventTable()->getEvent($event_id);
                 
                 try{
                     
                    $paginator=$this->getRegisterTable()->getEventParticipant($event_id,true);
                    $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
                    $paginator->setItemCountPerPage(10);                    

                    $viewmodel=new ViewModel(array(
                        'paginator' => $paginator,
                        'eventID'   => $event_id, 
                        'event'     => $pendingEvent,                       
                        'flashMessages' => $this->flashMessenger()->getMessages()
                    ));
                    return $viewmodel;
                    
                 }catch (\Exception $e){
                    return $this->redirect()->toRoute('events');
                 }                
          }
          return $this->redirect()->toRoute('events');
        } else {
            return $this->redirect()->toRoute('Login');
        } 
    }
   
    public function addAction()
    {
        $this->layout()->setTemplate('layout/eventparticipantlayout');
        $event_id = $this->params()->fromRoute('id');
        $this->layout()->id=$event_id;
        
        if ($this->getAuthService()->getIdentity()) {

            $userinfo = $this->getUserInfo();
            $this->layout()->role= $userinfo->ROLE;
            $this->layout()->user=$userinfo->USERNAME;
            
            $form=new RegisterForm();
            
            $pendingEvent = $this->getEventTable()->getEvent($event_id);            
            
            $viewmodel=new ViewModel(array(
                'form' => $form,
                'event' => $pendingEvent,
                'id'    => $event_id,
                'type'=>'add'
            ));
            return $viewmodel;
            
        }else {
            return $this->redirect()->toRoute('Login');
        }   
    }
   
    public function editAction()
    {
        $this->layout()->setTemplate('layout/eventparticipantlayout');
        $event_id = $this->params()->fromRoute('id');
        $this->layout()->id=$event_id;
        
        if ($this->getAuthService()->getIdentity()) {
            
            $userinfo = $this->getUserInfo();
            $this->layout()->role= $userinfo->ROLE;
            $this->layout()->user=$userinfo->USERNAME;
            
            $form=new RegisterForm();
            
            $pendingEvent = $this->getEventTable()->getEvent($event_id);
            $participant_id=$this->params()->fromRoute('param');
            
            $participant_Phone=$this->getParticipantPhoneTable()->getParticipantPhone($participant_id);
            $participant_Email=$this->getParticipantEmailTable()->getParticipantEmail($participant_id);
            $participant = $this->getParticipantTable()->getParticipant($participant_id);
            $participant->PHONE=$participant_Phone->PHONE;
            $participant->EMAIL=$participant_Email->EMAIL;
            $form->bind($participant);
            
            $viewModel = new ViewModel(array(
            'form' => $form,
            'event' => $pendingEvent,
            'id' => $this->params()->fromRoute('id'),
            'type'=>'edit'
            ));
            
            $viewModel->setTemplate('events/event-participant/add');
            return $viewModel;
            
        }else {
            return $this->redirect()->toRoute('Login');
        }
    }
    
    public function processAction()
    {
        $this->layout()->setTemplate('layout/eventparticipantlayout');
        $event_id = $this->params()->fromRoute('id');
        $this->layout()->id=$event_id;
        
        if ($this->getAuthService ()->getIdentity ()) {
			
			$userinfo = $this->getUserInfo ();
			$this->layout ()->role = $userinfo->ROLE;
			$this->layout ()->user = $userinfo->USERNAME;
			
			if (! $this->request->isPost ()) {
				return $this->redirect ()->toRoute ( NULL, array (
						'controller' => 'EventParticipant',
						'action' => 'index' 
				) );
			}			
			
			$form = new RegisterForm ();
            $pendingEvent = $this->getEventTable()->getEvent($event_id);
			
			$post = $this->request->getPost ();
			$form->setData ( $post );

			if (! $form->isValid ()) {
				$model = new ViewModel ( array (
						'form' => $form,
						'event' => $pendingEvent,
                        'id' => $event_id
				) );
				$model->setTemplate ( 'events/event-participant/add' );
				return $model;
			}
			
			$data=$form->getData();		
            $this->getDbConnection()->beginTransaction();
            
			try{			    
    			    if(!isset($data['ID'])||$data['ID']==0){
    			        $data = $this->processData($data);
    			        $this->createParticipant($data,0);
    			    }
    			    else{
    			        $this->createParticipant($data,1);
    			    }
    			     
    			    $data=$this->processRegistrationData($data);
    			    $this->createRegister($data);
    			     
    			    $this->flashMessenger()->addMessage('Participant '.$data['FIRST_NAME']." ".$data['LAST_NAME'].' is sucessfully added!');
    			    $this->getDbConnection()->commit();
			}
			catch (\Exception $ex){
			    $this->getDbConnection()->rollback();
			    $this->flashMessenger()->addMessage('Participant registration is failed!'.$data['ID']);
			}
			
			return $this->redirect()->toRoute('events',array( 'controller'=> 'EventParticipant','action' => 'index','id'=>$event_id));
			
		} else {
			return $this->redirect ()->toRoute ( 'Login' );
		}
    }
    
    public function viewProfileAction()
    {
        $this->layout()->setTemplate('layout/eventparticipantlayout');
        $event_id = $this->params()->fromRoute('id');
        $this->layout()->id=$event_id;
        
        if ($this->getAuthService()->getIdentity()) {
            
            $userinfo = $this->getUserInfo();
            $this->layout()->role= $userinfo->ROLE;
            $this->layout()->user=$userinfo->USERNAME;
            
            if (! $userinfo->ROLE == 'admin') {
                return $this->redirect()->toRoute('Login');
            }
            
            $event = $this->getEventTable()->getEvent($event_id);            
            $participant = $this->getParticipantTable()->getParticipant($this->params()->fromRoute('param'));
            $participated_events=$this->getRegisterTable()->getParticipatedEvents($participant->ID);
            
            foreach ($participated_events as $eventP){
                $participated_event[] = $this->getEventTable()->getEvent($eventP->FK_EVENT_ID);
            }
            
            $viewmodel=new ViewModel(array(
                'event' => $event,
                'participant' => $participant,
                'participated_events'=>$participated_event,
            ));
            return $viewmodel;
        }
        return $this->redirect()->toRoute('Login');
    }    
    
    
    public function emailAction()
    {
        $this->layout()->setTemplate('layout/additionallayout');
    
        if ($this->getAuthService()->getIdentity()) {
            return $this->redirect()->toUrl('http://www.gmail.com');
        }else {
            return $this->redirect()->toRoute('Login');
        }
    }
}